const Subscription = require('egg').Subscription;
const crypto = require('crypto');

class sendSms extends Subscription {
  // 通过 schedule 属性来设置定时任务的执行间隔等配置
  static get schedule() {
    return {
      type: 'worker', // 指定所有的 worker 都需要执行
      immediate: true,
    };
  }

  // subscribe 是真正定时任务执行时被运行的函数
  async subscribe() {
    const ctx = this.ctx;
    const app = ctx.app;
    if (app.isRunSms) {
      return
    }
    app.isRunSms = true
    const { mysql } = app;
    let userInfo;

    do {
      try {
        userInfo = await mysql.get('jiaolan_user', {
          sms_status: 1
        });
        if (!userInfo) break;
        await ctx.service.user.sendSms888(userInfo);
        await mysql.update('jiaolan_user', { sms_status: 2 }, { where: { openid: userInfo.openid } })
      } catch (ex) {
        console.log('发送失败', ex.message)
        await mysql.update('jiaolan_user', { sms_status: 9 }, { where: { openid: userInfo.openid } })
      }
    } while (true)
    app.isRunSms = false


    // const nonce = '63f20325467941719551bf35d6bff78f'
    // const timesteamp = Math.floor(Date.now() / 1000);
    // const { smsKey: key, smsURL } = app.weixin;
    // const sortSignature = [nonce, timesteamp, key].sort().join('');
    // const Signature = crypto.createHmac('sha256', key, { encoding: "utf8" }).update(sortSignature).digest('hex');
    // ctx.curl(`${smsURL}/sms/send?timesteamp=${timesteamp}&nonce=${nonce}`, {
    //   dataType: 'json',
    //   headers: {
    //     'X-04-Hmac-Signature': Signature
    //   },
    //   data: {
    //     outId: "xxxxx",
    //     phoneNumbers: '15024444920',
    //     templateCode: "1818",
    //     templateParam: JSON.stringify({
    //       code1: "1",
    //       code2: "2",
    //       code: '0',
    //       code4: '4'
    //     })
    //   }
    // })
    // setTimeout(() => {
    //   mysql.update('jiaolan_user', { sms_status: 2 }, {
    //     where: {
    //       openid: userInfo.openid,
    //       sms_time: new Date()
    //     }
    //   }).then(() => {
    //     app.isRunSms = false
    //   })
    //
    // }, 5000)
  }
}

module.exports = sendSms;
